package com.anosine.gpsl.android.ui.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.entity.FamilyNumber;
import com.anosine.gpsl.android.entity.FamilyNumberList;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.ModifyPwdInfo;
import com.anosine.gpsl.android.presenter.BasePresenterActivity;
import com.anosine.gpsl.android.presenter.FamilyNumberListPresenter;
import com.anosine.gpsl.android.ui.FamilyNumberListView;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.ShowConfirmDlgA;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
/**
 * @Title: FamilyNumberActivity
 * @Package com.anosine.gpsl.android.ui.activity
 * @Description:
 * @author: sunny
 * @date: 2015-12-1
 * @version V1.0
 */
public class FamilyNumberActivity extends BasePresenterActivity implements
		FamilyNumberListView {
	@ViewInject(R.id.content_tv_title)
	TextView title;
	@ViewInject(R.id.lv)
	ListView lv;
	FamilyNumberList familyNumber;
	@ViewInject(R.id.btn_right)
	Button addBtn;
	Login userInfo;
	/**
	 * @Title: BackOnClick(View v)
	 * @Description: 返回按钮的点击事件，点击关闭当前activity
	 * @param: View v
	 * @return: 无
	 * @throws
	 */
	@OnClick(R.id.button_left)
	private void BackOnClick(View v) {
		finish();
	}
	/**
	 * @Title: onCreate(Bundle savedInstanceState)
	 * @Description: 初始化
	 * @param: 无
	 * @return: 无
	 * @throws
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_familynumber_layout);
		ViewUtils.inject(this);
		title.setText("亲情号");
		initActivityOfgetFamilyNumber();
		addBtn.setText("添加");
		addBtn.setOnClickListener(new OnClickListener() {
			/**
			 * @Title: onClick(View v)
			 * @Description: 重写onClick(View v)
			 * @param: View
			 * @return: 无
			 * @throws
			 */
			@Override
			public void onClick(View v) {
				 boolean isHaveAdmin=false;
		    	 Login info= UserInfoProxy.getInstance().getLoginInfo();  
				  for(int i=0;i<GPSLApp.mActive.size();i++){
	        		  if((GPSLApp.mActive.get(i).hid).equals(info.holdid)){
	        			  isHaveAdmin=true;
	        		  }
	        		}
				  if(isHaveAdmin){
					  Intent intent1=new Intent(FamilyNumberActivity.this,AddFamilyNumberActivity.class);
		        	  startActivity(intent1);
				  }else{
					  ToastHelper.toast("您没有权限添加亲情号！");
				  }
				
			}
		});
		familyNumber=new FamilyNumberList();
	}
	/**
	 * @Title: initActivityOfgetFamilyNumber()
	 * @Description: 调用亲情号列表接口
	 * @param: 无
	 * @return: 无
	 * @throws
	 */
	public void initActivityOfgetFamilyNumber() {
		// 将合成的URL传给服务器 c7787d5ab3d510457e418c1bf9eef84d
		FamilyNumberListPresenter presenter = new FamilyNumberListPresenter(this);
		userInfo = UserInfoProxy.getInstance().getLoginInfo();
		presenter.loadFamilyNumberList(userInfo.userMd5);
		
	}
	/**
	 * @Title: replaceAll(StringBuffer sb, String oldStr, String newStr)
	 * @Description: 替换字符
	 * @param: sb 父字符串
	 * @param: oldStr 旧的字符串（替换前的字符）
	 * @param: newStr 新的字符串（替换后的字符）
	 * @return: 无
	 * @throws
	 */
	public static StringBuffer replaceAll(StringBuffer sb, String oldStr, String newStr) {
        int i = sb.indexOf(oldStr);
        int oldLen = oldStr.length();
        int newLen = newStr.length();
        while (i > -1) {
            sb.delete(i, i + oldLen);
            sb.insert(i, newStr);
            i = sb.indexOf(oldStr, i + newLen);
        }
        return sb;
    }
	/**
	 * @Title: setFamilyNumberList(String t)
	 * @Description: 解析亲情号列表接口返回信息
	 * @param: t
	 * @return: 无
	 * @throws
	 */
	@Override
	public void setFamilyNumberList(String t) {
		String s1=t.substring(0, t.length()-1);
		String s2=s1.substring(1,s1.length());
        String [] List = s2.split("\\],\\[");
		StringBuffer sb1 = new StringBuffer(List[0]);
		StringBuffer sb2 = new StringBuffer(List[List.length-1]);

        StringBuffer sb11=replaceAll(sb1, "[", "");
        StringBuffer sb22=replaceAll(sb2, "]", "");
        List[0]=sb11.toString();
        List[List.length-1]=sb22.toString();
        
        List<FamilyNumber> familynum=new ArrayList<FamilyNumber>();

        for(int i=0;i<List.length;i++)
		{
            FamilyNumber fn=new FamilyNumber();
    		StringBuffer sbitem1 = new StringBuffer(List[i]);
            StringBuffer sbitem2=replaceAll(sbitem1, "\"", "");
            String [] ListItem=sbitem2.toString().split(",");
        	fn.name=ListItem[1];
        	fn.number=ListItem[0];
            familynum.add(fn);
		}        
     
		if (familynum.size() == 0) {
			ToastHelper.toast("没有亲情号！");
		} else {
	        familyNumber.list=familynum;
			MyAdapter adapter = new MyAdapter(this);
			lv.setAdapter(adapter);
		}
	}
	/**
	 * @Title: MyAdapter
	 * @Description: 亲情列表的adapter
	 * @throws
	 */
	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		/**
		 * @Title: MyAdapter(Context context)
		 * @Description: 初始化
		 * @param: context
		 * @throws
		 */
		public MyAdapter(Context context) {

			this.mInflater = LayoutInflater.from(context);

		}
		/**
		 * @Title: getCount()
		 * @Description: 亲情号个数
		 * @param: 无
		 * @return: int
		 * @throws
		 */
		@Override
		public int getCount() {

			return familyNumber.list.size();

		}
		/**
		 * @Title: getItem(int arg0)
		 * @Description: 获取亲情号列表单个item信息
		 * @param: arg0
		 * @return: Object
		 * @throws
		 */
		@Override
		public Object getItem(int arg0) {
			return familyNumber.list.get(arg0);
		}
		/**
		 * @Title: getItemId(int arg0)
		 * @Description: 获取
		 * @param: arg0
		 * @return: long
		 * @throws
		 */
		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {

			ViewHolder holder = null;

			if (view == null) {

				holder = new ViewHolder();

				view = mInflater.inflate(
						R.layout.activity_familynumber_lv_item, null);

				holder.number = (TextView) view.findViewById(R.id.number);
				holder.name=(TextView)view.findViewById(R.id.name);
				holder.delete=(LinearLayout)view.findViewById(R.id.delete);
						
				view.setTag(holder);

			} else {

				holder = (ViewHolder) view.getTag();

			}

			 holder.number.setText(familyNumber.list.get(position).number);
			 holder.name.setText(familyNumber.list.get(position).name);
			 holder.delete.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					 boolean isHaveAdmin=false;
			    	 Login info= UserInfoProxy.getInstance().getLoginInfo();  
					  for(int i=0;i<GPSLApp.mActive.size();i++){
		        		  if((GPSLApp.mActive.get(i).hid).equals(info.holdid)){
		        			  isHaveAdmin=true;
		        		  }
		        		}
					  if(isHaveAdmin){
						  final ShowConfirmDlgA dialog = new ShowConfirmDlgA(
									FamilyNumberActivity.this, "确定要删除此亲情号吗？","删除");
							TextView cancel = dialog.getCancel();
							TextView ok = dialog.getOk();
							ok.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {					    	  
									  gotoDel(familyNumber.list.get(position).number);				        	  
									  dialog.dismiss();
								}
							});
							cancel.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									dialog.dismiss();
								}
							});
							dialog.show();
					  }else{
		        		  ToastHelper.toast("您没有权限进行删除！");
		        	  }		
					
					return false;
				}

				
			});
			return view;

		}

	}
	//删除亲情号
	private void gotoDel(String number) {
		RequestParams params = new RequestParams();
		params.addBodyParameter("usermd5", userInfo.userMd5);
		params.addBodyParameter("familynumbers", number);
		SendHttpUtils sendHttp = new SendHttpUtils();
		TypeToken type = new TypeToken<ModifyPwdInfo>() {
		};
		String url = String.format("%1s/%2s", AppConstants.sCommonUrl,
				WebConstants.Do_DelFamilyNumbers_Action);
		sendHttp.doRequest(url, params, type, new HttpRequestListener<ModifyPwdInfo>() {
			/**
			 * @Title: onSuccess(String result, Login t)
			 * @Description: 解析成功做的操作
			 * @param: result json
			 * @param: t 登录的实体类
			 * @return: 无
			 * @throws
			 */
			@Override
			public void onSuccess(String result, ModifyPwdInfo t) {
					if("msg_delete_succees".equals(t.message)){
						ToastHelper.toast("删除亲情用户成功！");
						//此处要刷新
						initActivityOfgetFamilyNumber();
						
					}else if("msg_no_familynumbers".equals(t.message)){
						ToastHelper.toast("你要删除的不是亲情用户！");
					}else if("msg_delete_fail".equals(t.message)){
						ToastHelper.toast("你不能删除自己的车辆！");
					}else if("msg_fail".equals(t.message)){
						ToastHelper.toast("参数错误！");
					}

			}
			/**
			 * @Title: onFailure(String error)
			 * @Description: 解析失败做的操作
			 * @param: error 错误信息
			 * @return: 无
			 * @throws
			 */
			@Override
			public void onFailure(String error) {
				ToastHelper.toast(error);
			}
		});
	}
	public class ViewHolder

	{

		public TextView number,name;
		LinearLayout delete;
	}
}
